package com.bops.biz.permission;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class Grant {

    public Grant(String grantText) {
        this.grantText = grantText;
        parse();
    }

    private void parse() {
        int index = grantText.indexOf("?");
        if (index == -1) {
            grantUrl = grantText;
            return;
        }
        grantUrl = grantText.substring(0, index);
        String args = grantText.substring(index + 1);
        String sp1[] = args.split(","); // 以,分割参数
        for (String s : sp1) {
            if (s != null) {
                int indexDeng = s.indexOf("=");
                if (indexDeng != -1) {
                    String key = s.substring(0, indexDeng);
                    String value = s.substring(indexDeng + 1);
                    if (params == null) {
                        params = new HashMap<String, String>();
                    }
                    params.put(key, value);
                }
            }
        }
    }

    /**
     * 检查URL是否相等，并且检查参数是否相等
     * 
     * @param url
     * @param request
     * @return
     */
    public boolean checkUserGrant(String url, HttpServletRequest request) {
        if (url == null) {
            return false;
        }
        if (url.equals(grantUrl)) {
            if (params != null) {
                Iterator<String> it = params.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    if (key != null) {
                        Object obj = request.getParameter(key);
                        Object value = params.get(key);
                        if (obj == null) {
                            if (value != null) {
                                return false;
                            }
                        } else if (!obj.equals(value)) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        return false;
    }

    private String              grantText;
    private String              grantUrl;
    private Map<String, String> params;
}
